package com.shixun.dds_11.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shixun.dds_11.JWT.JwtClaimsConstant;
import com.shixun.dds_11.JWT.JwtProperties;
import com.shixun.dds_11.JWT.JwtUtil;
import com.shixun.dds_11.context.BaseContext;
import com.shixun.dds_11.entity.DdsUser;
import com.shixun.dds_11.entity.User;
import com.shixun.dds_11.mapper.DdsUserMapper;
import com.shixun.dds_11.mapper.UserMapper;
import com.shixun.dds_11.result.Result;
import com.shixun.dds_11.service.IDdsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YSP
 * @since 2024-07-05
 */
@Service
@Slf4j
public class DdsUserServiceImpl extends ServiceImpl<DdsUserMapper, DdsUser> implements IDdsUserService {

    @Autowired
    DdsUserMapper ddsUserMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public Result login(DdsUser user) {

        QueryWrapper<DdsUser> queryWrapper=new QueryWrapper<DdsUser>()
                .eq("username",user.getUsername())
                .eq("password",user.getPassword());
        DdsUser ddsUser = ddsUserMapper.selectOne(queryWrapper);
        if(ddsUser==null)
            return Result.error("密码错误或用户名不存在");
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, ddsUser.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        return Result.success(token);
    }


    @Override
    @Transactional
    public void register(DdsUser ddsUser) {
        ddsUserMapper.insert(ddsUser);
        User user=new User();
        user.setId(ddsUser.getId());
        user.setUsername(ddsUser.getUsername());
        userMapper.add(user);
    }
}
